package com.g2room.myuall.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/** 
* 
* @author Jiangpin 
*/ 
public class CompressImgUtils {
	
	/**
	 * 图片压缩测试
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		compressImg(dir);
	}
	
	/** 
	* @param f 图片文件
	* @param targetDir 图片目标目录 
	* @param per 百分比 
	*/ 
	private static void  compress(File f, float per){
		Image src; 
		try {
			src = ImageIO.read(f); //构造Image对象
			String fileType = f.getName().substring(f.getName().lastIndexOf(".") + 1);
			String targetPath = targetDir + f.getPath().replace(dir, "");
			if(!fileType.equalsIgnoreCase("png") && !fileType.equalsIgnoreCase("bmp") 
					&& !fileType.equalsIgnoreCase("jpeg") 
					&& !fileType.equalsIgnoreCase("jpg") 
					&& !fileType.equalsIgnoreCase("gif")) {
				if(fileType.equalsIgnoreCase("ico")) return;
				// 直接拷贝
				copyFile(f, targetPath, false);
				return;
			}
			int w=src.getWidth(null); //得到源图宽
			int h=src.getHeight(null);

			if(w > 2500) {
				h = h * 2500 / w;
				w = 2500;
			}
			
			BufferedImage tag = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);	            	              
			tag.getGraphics().drawImage(src.getScaledInstance(w, h,  Image.SCALE_SMOOTH), 0,0,null);

			dirExist(targetPath.replaceAll(f.getName(), ""));
			FileOutputStream newImage=new FileOutputStream(targetPath); //输出到文件流 
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage); 
			JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag); 
			/* 压缩质量 */ 
			jep.setQuality(per, true); 
			encoder.encode(tag, jep); 
			newImage.flush();
			newImage.close(); 
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
	}
 
	private static void dirExist(String dir) {
	 	File file = new File(dir);
	 	if(!file.exists()) {
	 		file.mkdirs();
	 	}
	}
 
}